import {
	createRouter,
	createWebHistory
} from "vue-router";


const Home = () => import('@/views/Home.vue');
const Category = () => import('@/components/page/Cart.vue');
const Cart = () => import('@/components/page/Cart.vue');
const Center = () => import('@/components/page/Center.vue');
const Search = () => import('@/components/search/search.vue');
const Login = () => import('@/components/user/Login.vue');
const Registered = () => import('@/components/user/Registered.vue');
const UserInfo = () => import('@/components/page/UserInfo.vue');
const Order = () => import('@/components/page/Order');
const Book = () => import('@/components/page//Book.vue');
const BookDetail = () => import('@/components/book/BookDetail.vue');

const routes = [


	{
		path: '/login',
		redirect: {
			name: 'Login',
		}
	},
	{
		path: "/",
		name: "Home",
		component: Home,
	},

	{
		path: "/category",
		name: "Category",
		component: Category,
	},


	{
		path: "/book",
		name: "Book",
		component: Book,
	},

	{
		path:"/bookdetail",
		name: "BookDetail",
		component:BookDetail,
	},

	{
		path: "/cart",
		name: "Cart",
		component: Cart,
		meta: {
			role: 'P'
		},
	},

	{
		path: "/search",
		name: "Search",
		component: Search,
	},

	{
		path: "/center",
		name: "Center",
		component: Center,
	},

	{
		path: "/useredit",
		name: "UserInfo",
		component: UserInfo,
		meta: {
			role: 'P'
		},
	},

	{
		path: "/order",
		name: "Order",
		component: Order,
		meta: {
			role: 'P'
		},
	},

	{
		path: "/login",
		name: "Login",
		component: Login,
	},

	{
		path: "/registered",
		name: "Registered",
		component: Registered,
	},

];

const router = createRouter({
	history: createWebHistory(process.env.BASE_URL),
	routes,
});


router.beforeEach((to, form, next) => {
	//1.在任意一个地址跳转的时候,从本地存储中获取当前登录的角色值
	let role = localStorage.getItem('role');

	//没有限制的路由地址也能正常访问
	if (to.meta.role == undefined || to.meta.role == '') {
		next();
		return;
	}

	//进入后台首页：role是否与规则中的要求匹配
	//判断即将进入的路由规则中限制的访问角色规则 是否与当前登录者的角色匹配

	if (to.meta.role == role) {
		//继续进入
		next();
		return;
	}
	//以上都不需要的路由,默认跳转返回登录页
	router.replace('/login').catch((error) => {


	})

})

export default router;
